//
//  ViewController.m
//  20-XML
//
//  Created by Snow on 16/8/10.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "ViewController.h"
#import "XMLReader.h"
#import "ModelOfXML.h"
@interface ViewController ()<NSXMLParserDelegate>
@property (nonatomic, strong) NSMutableArray *arrayOfSax;
@property (nonatomic, copy) NSString *currentElementName;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self handleData];
    [self handleData1];
   
}
- (void)handleData
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Cartoon" ofType:@"xml"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSDictionary *dic = [XMLReader dictionaryForXMLData:data error:&error];
    NSLog(@"%@", dic);
}
- (void)handleData1
{
    NSString *string = [[NSBundle mainBundle] pathForResource:@"Cartoon" ofType:@"xml"];
    NSData *data = [NSData dataWithContentsOfFile:string];
    NSXMLParser *xml = [[NSXMLParser alloc] initWithData:data];
    xml.delegate = self;
    [xml parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser {
    self.arrayOfSax = [NSMutableArray array];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
    NSLog(@"%@", _arrayOfSax);
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {
    _currentElementName = elementName;
    if ([_currentElementName isEqualToString:@"AlbumInfo"]) {
        ModelOfXML *model = [ModelOfXML new];
        [self.arrayOfSax addObject:model];
    }
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (_currentElementName) {
        ModelOfXML *model = [_arrayOfSax lastObject];
        [model setValue:string forKey:_currentElementName];
    }
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"报错原因：%@", parseError);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    _currentElementName = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
